package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.vo.R;
import com.itheima.dto.systemInfo.ConfigDto;
import com.itheima.dto.systemInfo.BaseInfoDto;
import com.itheima.dto.user.SysUserDto;
import com.itheima.dto.systemInfo.YddCateDto;
import com.itheima.dto.user.UserDto;
import com.itheima.dto.yddUser.SysUserInfo;
import com.itheima.entity.*;
import com.itheima.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@RequestMapping("/index")
@RestController
@Slf4j
public class IndexController {
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private MenuService menuService;
    @Autowired
    private RoleMenuService roleMenuService;
    @Autowired
    private DictService dictService;

    // 文章分类
    @Autowired
    private YddCateService cateService;

    //广告位
    @Autowired
    private YddAdvposService yddAdvposService;

    //标签
    @Autowired
    private YddTagService tagService;

    //文章
    @Autowired
    private YddArticleService articleService;

    //广告图
    @Autowired
    private YddAdvimgService advimgService;

    //前端用户
    @Autowired
    private YddUserService yddUserService;

    @Autowired
    public ConfigService configService;

    /**
     * 登录
     * @param sysUser
     * @return
     */
    @PostMapping("/login")
    public R<Object> login(@RequestBody SysUser sysUser) {
        log.info("SysUser-{}", sysUser);
        String mobile = sysUser.getLoginName();
        LambdaQueryWrapper<SysUser> ylqw = new LambdaQueryWrapper<>();
        ylqw.eq(SysUser::getLoginName, sysUser.getLoginName());
        SysUser userServiceOne = userService.getOne(ylqw);
        if (userServiceOne == null) {
            return R.error("用户不存在", 1000);
        }
        if (!DigestUtils.md5DigestAsHex(sysUser.getPassword().getBytes()).equals(userServiceOne.getPassword())) {
            return R.error("密码错误", 1000);
        }
        if(userServiceOne.getStatus()==0){
            return R.error("用于已冻结", 1000);
        }
        HashMap<String, String> map = new HashMap<>();
        map.put("token", userServiceOne.getId());
        return R.success(map);
    }

    @PostMapping("/profile")
    public R<SysUserDto> profile(HttpServletRequest request) {
        SysUserDto sysUserDto = new SysUserDto();
        String token = request.getHeader("x-token");
        log.info("x-token-{}", token);
        //查询user信息setUserInfo
        SysUser userServiceById = userService.getById(token);
        SysUserInfo sysUserInfo = new SysUserInfo();
        BeanUtils.copyProperties(userServiceById, sysUserInfo);
        //String[] roleId = userServiceById.getRoleId();
        String roleIds = userServiceById.getRoleId();
        String roleId = roleIds.substring(2, roleIds.length() - 2);//处理rolId
        sysUserInfo.setRoleId(roleId);
        String rolename = roleService.getById(roleId).getName();
        sysUserInfo.setRolename(new String[]{rolename});
        sysUserDto.setUserInfo(sysUserInfo);
        //查询menu信息type=1,关系表rolemenu
        LambdaQueryWrapper<SysRoleMenu> sysRoleMenuLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysRoleMenuLambdaQueryWrapper.eq(SysRoleMenu::getRoleId, roleId);
        List<SysRoleMenu> sysRoleMenus = roleMenuService.list(sysRoleMenuLambdaQueryWrapper);

        /*List<SysMenu> sysMenus = sysRoleMenus.stream().map(item -> {
            SysMenu sysMenu = new SysMenu();
            String menuId = item.getMenuId();
            LambdaQueryWrapper<SysMenu> sysMenuLambdaQueryWrapper = new LambdaQueryWrapper<>();
            sysMenuLambdaQueryWrapper.eq(SysMenu::getType, 1);
            sysMenuLambdaQueryWrapper.eq(SysMenu::getId, menuId);
            SysMenu menuServiceOne = menuService.getOne(sysMenuLambdaQueryWrapper);
            if (null != menuServiceOne) {
                sysMenu = menuServiceOne;
            }
            return sysMenu;
        }).collect(Collectors.toList());*/
        List<String> menuIds = sysRoleMenus.stream().map(item -> {
            return item.getMenuId();
        }).collect(Collectors.toList());
        LambdaQueryWrapper<SysMenu> sysMenuLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysMenuLambdaQueryWrapper.eq(SysMenu::getType, 1);
        //sysMenuLambdaQueryWrapper.eq(SysMenu::getIsShow,1);
        sysMenuLambdaQueryWrapper.in(SysMenu::getId, menuIds);
        sysUserDto.setMenuList(menuService.list(sysMenuLambdaQueryWrapper));
        //查询dict信息
        LambdaQueryWrapper<SysDict> sysDictLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysDictLambdaQueryWrapper.groupBy(SysDict::getType);
        List<SysDict> list = dictService.list(sysDictLambdaQueryWrapper);
        List<String> type = new ArrayList<>();
        list.forEach((item) -> {
            type.add(item.getType());
        });

        HashMap dictsList = new HashMap();
        type.stream().map(item -> {
            LambdaQueryWrapper<SysDict> sysDictLambdaQueryWrapper1 = new LambdaQueryWrapper<>();
            sysDictLambdaQueryWrapper1.eq(SysDict::getType, item);
            List<SysDict> list1 = dictService.list(sysDictLambdaQueryWrapper1);

            HashMap<String, String> dicts = new HashMap();
            list1.forEach(l -> {
                dicts.put(l.getValue(), l.getLabel());
            });
            dictsList.put(item, dicts);
            return item;
        }).collect(Collectors.toList());
        sysUserDto.setDictsList(dictsList);
        return R.success(sysUserDto);
    }

    /**
     * 后台主页基本信息
     * @return
     */
    @GetMapping("/baseInfo")
    public R<BaseInfoDto> baseInfo() {
        //返回的数据
        BaseInfoDto baseInfoDto = new BaseInfoDto();
        //所有分类信息
        ArrayList<YddCateDto> yddCateDtoList = new ArrayList<>();
        List<YddCate> cateList = cateService.list();
        for (YddCate yddCate : cateList) {
            YddCateDto yddCateDto = new YddCateDto();
            BeanUtils.copyProperties(yddCate, yddCateDto);
            LambdaQueryWrapper<YddArticle> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(YddArticle::getCateid, yddCate.getId());
            int num = articleService.count(wrapper);
            yddCateDto.setNum(num);
            yddCateDtoList.add(yddCateDto);
        }
        baseInfoDto.setAllCate(yddCateDtoList);
        //广告位数量
        int advposNum = yddAdvposService.count();
        baseInfoDto.setAdvposNum(advposNum);
        //标签数量
        int tagNum = tagService.count();
        baseInfoDto.setTagNum(tagNum);
        //管理人员数量
        int adminNum = userService.count();
        baseInfoDto.setAdminNum(adminNum);
        //平台文章总数
        int articleNum = articleService.count();
        baseInfoDto.setArticleNum(articleNum);
        //文章分类数量
        int cateNum = cateService.count();
        baseInfoDto.setCateNum(cateNum);
        //广告图数量
        int advimgNum = advimgService.count();
        baseInfoDto.setAdvimgNum(advimgNum);
        //新注册的用户
        Page<YddUser> yddUserPage = new Page<>(1, 7);
        LambdaQueryWrapper<YddUser> userWrapper = new LambdaQueryWrapper<>();
        userWrapper.orderByDesc(YddUser::getId);
        yddUserService.page(yddUserPage, userWrapper);
        baseInfoDto.setNewUser(yddUserPage.getRecords());
        //最新文章
        Page<YddArticle> yddArticlePage = new Page<>(1, 7);
        LambdaQueryWrapper<YddArticle> articleWrapper = new LambdaQueryWrapper<>();
        articleWrapper.orderByDesc(YddArticle::getClick);
        articleService.page(yddArticlePage, articleWrapper);
        baseInfoDto.setHotArticle(yddArticlePage.getRecords());
        //用户的 总数 以及 男女的数量
        UserDto userDto = new UserDto();
        int total = yddUserService.count(); //总人数
        LambdaQueryWrapper<YddUser> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(YddUser::getSex, 0);
        int userMan = yddUserService.count(wrapper1); //男
        LambdaQueryWrapper<YddUser> wrapper2 = new LambdaQueryWrapper<>();
        wrapper1.eq(YddUser::getSex, 1);
        int userWoman = yddUserService.count(wrapper2); //女
        userDto.setTotal(total);
        userDto.setUserMan(userMan);
        userDto.setUserWoman(userWoman);
        baseInfoDto.setUser(userDto);
        //返回
        return R.success(baseInfoDto);
    }

    /**
     *
     * @return
     */
    @GetMapping("/getConfig")
    public R<ConfigDto> getConfig() {
        ConfigDto configDto = new ConfigDto();
        String loginTitle = config("login_title", configService);
        String loginBg = config("login_bg", configService);
        String systemName = config("system_name", configService);
        String systemLogo = config("system_logo", configService);
        String webIco = config("web_ico", configService);
        configDto.setLoginTitle(loginTitle);
        configDto.setLoginBg(loginBg);
        configDto.setSystemName(systemName);
        configDto.setSystemLogo(systemLogo);
        configDto.setWebIco(webIco);
        return R.success(configDto);
    }

    /**
     * 获取attr_value 封装的方法
     * @param s
     * @param configService
     * @return
     */
    public static String config(String s, ConfigService configService) {
        LambdaQueryWrapper<SysConfig> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(SysConfig::getAttrKey, s);
        SysConfig one = configService.getOne(wrapper1);
        String config = one.getAttrValue();
        return config;
    }
}
